import 'dart:typed_data';

import 'package:erp/data/api/process_api.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path/path.dart';

import 'load_image.dart';

class ProcessAttachment {
  final int? id;
  final String? path;
  final String? name;
  final Uint8List? bytes;
  final Stream<List<int>>? readStream;
  final int? size;

  ProcessAttachment({
    this.id,
    this.path,
    this.name,
    this.bytes,
    this.readStream,
    this.size,
  });
}

class ProcessAttachmentUpload extends StatefulWidget {
  final List<ProcessAttachment> fileList;
  final Future<bool> Function(FilePickerResult? result)? onUpload;

  ProcessAttachmentUpload({Key? key, required this.fileList, this.onUpload});

  @override
  State<StatefulWidget> createState() {
    return ProcessAttachmentUploadState(
      fileList: fileList,
      onUpload: onUpload,
    );
  }
}

class ProcessAttachmentUploadState extends State<ProcessAttachmentUpload> {
  final List<ProcessAttachment> fileList;
  final Future<bool> Function(FilePickerResult? result)? onUpload;

  ProcessAttachmentUploadState({required this.fileList, this.onUpload});

  @override
  Widget build(BuildContext context) {
    var uploadButton;
    uploadButton = Container(
      height: 50.h,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          LoadAssetImage('widgets/sale_project_plus', width: 16.w, height: 16.w),
          SizedBox(width: 10.w),
          Text(
            '上传文件',
            style: TextStyle(color: Color(0xFFCCCCCC), fontSize: 26.sp, fontWeight: FontWeight.w400),
          ),
        ],
      ),
    );
    // 水波纹
    uploadButton = Material(
      child: Ink(
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color: Color(0xffB3B3B3), width: 1.w),
          borderRadius: BorderRadius.all(Radius.circular(4.r)),
        ),
        child: InkWell(
          onTap: () async {
            FilePickerResult? result = await FilePicker.platform.pickFiles(
              allowMultiple: true,
              type: FileType.custom,
              allowedExtensions: ['jpg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'zip', 'rar'],
            );
            if (onUpload != null) {
              var flag = await onUpload!(result);
              if (flag) {
                setState(() {});
              }
            }
          },
          child: uploadButton,
        ),
      ),
    );

    /// 流程文件下载按钮组
    var files = fileList.asMap().entries.map(
      (entry) {
        int index = entry.key;
        ProcessAttachment file = entry.value;

        var buttons = [
          Material(
            child: Ink(
              decoration: BoxDecoration(
                color: Color(0xff4C88FF),
                borderRadius: BorderRadius.all(
                  Radius.circular(4.r),
                ),
              ),
              child: InkWell(
                onTap: () async {
                  // if exist id
                  var item = fileList[index];
                  if (item.id != null) {
                    await ProcessApi.deleteProcessFileById(item.id!);
                  }
                  setState(() {
                    fileList.removeAt(index);
                  });
                },
                child: Container(
                  alignment: AlignmentDirectional.center,
                  width: 60.w,
                  height: 30.h,
                  child: Text(
                    '删除',
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                  ),
                ),
              ),
            ),
          ),
        ];

        var fileButtonGroup = Container(
          width: buttons.length != 0 ? (buttons.length * 60 + (buttons.length - 1) * 10).w : 0,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: buttons,
          ),
        );

        return Padding(
          padding: EdgeInsets.only(top: 20.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                child: Row(
                  children: [
                    Image.asset(
                      'assets/images/zip.png',
                      width: 20.w,
                      height: 20.h,
                    ),
                    SizedBox(width: 10.w),
                    Text(
                      basename(file.path ?? ''),
                      style: TextStyle(color: Color(0xFF555555), fontSize: 14.sp),
                    ),
                  ],
                ),
              ),
              fileButtonGroup
            ],
          ),
        );
      },
    ).toList();

    return Container(
      child: Column(
        children: [
          uploadButton,
          Padding(
            padding: EdgeInsets.only(top: 20.h),
            child: Text(
              '※ 支持多种文件格式（单个文件大小不超过10M，总大小不超过50M）',
              style: TextStyle(color: Color(0xFF4C88FF), fontSize: 16.sp, fontWeight: FontWeight.w400),
            ),
          ),
          ...files
        ],
      ),
    );
  }
}
